package javatwo.annotation.course2.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Map;
import java.util.Set;

import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.scannotation.AnnotationDB;
import org.scannotation.WarUrlFinder;

@WebServlet(name = "coreServlet", urlPatterns = "/core")
public class CoreServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter pw = response.getWriter();

		try {

//			URL[] infURLs = WarUrlFinder.findWebInfLibClasspaths(this.getServletContext());
//			for(URL url:infURLs){
//				pw.println("Loading.. "+url+"<br/>");
//			}
			
			URL cpURL = WarUrlFinder.findWebInfClassesPath(this.getServletContext());
			
			AnnotationDB db = new AnnotationDB();
			db.scanArchives(cpURL);
			
			
			Map<String, Set<String>> annotationIndex = db.getAnnotationIndex();
			Set<String> sClassesNames = annotationIndex.get("javax.servlet.annotation.WebServlet");
			
			for (String sClassesName : sClassesNames) {
				pw.println(sClassesName+"<br/>");
				
				/**
				 * The default ClassPool returned by a static method ClassPool.getDefault() 
				 * searches the same path that the underlying JVM (Java virtual machine) has. 
				 * If a program is running on a web application server such as JBoss and Tomcat, 
				 * the ClassPool object may not be able to find user classes since such a web 
				 * application server uses multiple class loaders as well as the system class loader. 
				 * In that case, an additional class path must be registered to the ClassPool. 
				 * Suppose that pool refers to a ClassPool object:  
				 */
				ClassPool pool = ClassPool.getDefault();
				pool.insertClassPath(new ClassClassPath(this.getClass())); 
				
				CtClass cc = pool.get(sClassesName);
				Object[] all = cc.getAnnotations();
				WebServlet servlet = (WebServlet) all[0];
				String name = servlet.name();
				pw.println("<a href='."+servlet.urlPatterns()[0]+"'>name="+name+"</a><br/>");
			}
			

		} catch (Exception e) {
			// TODO Auto-generated catch block
			pw.println("<br/>");
			pw.println(e+"<br/>");
			StackTraceElement[] stacks = e.getStackTrace();
			for (StackTraceElement stack : stacks) {
				pw.println(stack + "<br/>");
			}

		}

		pw.close();
	}

}
